#include "sekai/PitchModel.h"
#include <assert.h>

void PitchModel::addNote(float start, float length, float f0) {

  if (time.size() == 0) {
    time.push_back(start);
    pitch.push_back(f0);
    startPos = start;
    endPos = start + length;
    time.push_back(start + 0.8 * length);
    pitch.push_back(f0);
  } else {
    time.push_back(start + 0.2 * length);
    pitch.push_back(f0);
    time.push_back(start + 0.5 * length);
    pitch.push_back(f0);
    time.push_back(start + 0.8 * length);
    pitch.push_back(f0);
    endPos = start + length;
  }
}
void PitchModel::fix() {
  int count = time.size();

  float lastf0 = pitch[count - 1];
  pitch.push_back(lastf0);
  time.push_back(endPos);
  count++;

  assert(time.size() == pitch.size());

  acc = gsl_interp_accel_alloc();
  cspline = gsl_spline_alloc(gsl_interp_cspline, count);

  gsl_spline_init(cspline, time.data(), pitch.data(), count);
}

float PitchModel::getF0atTime(float time) {
  if (time >= startPos && time <= endPos) {
    return gsl_spline_eval(cspline, (double)time, acc);
  }
  return 0.0;
}

float PitchModel::getLength() { return endPos; }
